package com.bt.interceptor;

import com.bt.constant.JwtClaimsConstant;
import com.bt.context.BaseContext;
import com.bt.properties.JwtProperties;
import com.bt.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description 检查前端令牌
 * @Author 张传康
 * @Date 2023-05-04 18:33
 */
@Component
@Slf4j
public class UserLoginCheckInterceptor implements HandlerInterceptor {

    @Autowired
    JwtProperties jwtProperties;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源

        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }

        //获取令牌
        String token = request.getHeader("token");

        //校验
        try {
            log.info("jwt校验:{}", token);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
            String yddUserId = claims.get(JwtClaimsConstant.YDD_USER_ID).toString();


            //对threadLocal setCurrentId()赋值
            BaseContext.setCurrentId(yddUserId);

            log.info("当前用户id：", yddUserId);




            //通过，放行
            return true;
        } catch (Exception ex) {
            //4、不通过，响应401状态码
            response.setStatus(401);
            return false;
        }
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        BaseContext.removeCurrentId();
    }
}
